﻿using System.Device.Location;
using Amicus_Place_Finder;
using Amicus_Place_Finder.Language;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;

namespace Facebook
{
    public static class FacebookAPI
    {

        public static string fb_client_id = "121665904703600", fb_client_secret = "2f2f4b9249d4c69ee0fcd630d3c46cfe";
        public static string fb_access_token = "121665904703600|QNGfCqw-8ftu7AH1taXxgkw65Fs";
        public static string fb_get_access_token = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials";
        public static string fb_Search_Page = "http://graph.facebook.com/search?type=page&q={0}";
        public static string fb_Info_Page = "http://graph.facebook.com/{0}";
        public static string fb_Get_Post_Page = "https://graph.facebook.com/{0}/feed?access_token={1}";
        public static string fb_Avatar = "http://graph.facebook.com/{0}/picture";
        public static string fb_Places_Search = "https://graph.facebook.com/search?type=place&value=1&center={0},{1}&distance={2}&access_token={3}";
        public static string fb_Places_Search_By_Name_Nearby = "https://graph.facebook.com/search?type=place&value=1&center={0},{1}&distance={2}&access_token={3}&q={4}";
        public static string fb_Places_Search_By_Name = "https://graph.facebook.com/search?type=place&q={0}&access_token=221984714612698|CB5j-m195o2BlWtfiGQV0RbsyNQ";
        public static string fb_Friend_List = "https://graph.facebook.com/me/friends?access_token={0}";

        public static List<FriendModel> ListFriends = new List<FriendModel>();

        public static void Set_FB_App_ID(string client_id, string client_secret)
        {
            fb_client_id = client_id;
            fb_client_secret = client_secret;
        }

        public static async Task<bool> Get_FB_Access_Token()
        {
            try
            {
                WebClient wc = new WebClient();
                string result = await wc.DownloadStringTaskAsync(new Uri(string.Format(fb_get_access_token, fb_client_id, fb_client_secret)));
                fb_access_token = result.Replace("access_token=", "");
                return true;
            }
            catch { return false; }
        }

        public static async Task<List<PlaceItem>> GetNearbyPlaces(double lat, double lo)
        {
            if (fb_access_token == "")
                await Get_FB_Access_Token();
            var list = new List<PlaceItem>();
            try
            {
                WebClient wc = new WebClient();
                var r = await wc.DownloadStringTaskAsync(new Uri(string.Format(fb_Places_Search, lat, lo, SettingUtils.Settings.MapSearchRadius, fb_access_token)));
                var jo = JObject.Parse(r);
                int count = 0;
                foreach (JObject item in (JArray)jo["data"])
                {
                    count++;
                    try
                    {
                        list.Add(new PlaceItem
                        {
                            ID=count,
                            Id = (string)item["id"],
                            Name = (string)item["name"],
                            latitude = (double)item["location"]["latitude"],
                            longitude = (double)item["location"]["longitude"],
                            address = (string)item["location"]["street"],
                            //street = (string)item["location"]["street"],
                            city = (string)item["location"]["city"],
                            state = (string)item["location"]["state"],
                            country = (string)item["location"]["country"],
                            zip = (string)item["location"]["zip"],
                            categoryName = (string)item["category_list"][0]["name"],
                            categoryId = (string)item["category_list"][0]["id"]
                        });
                    }
                    catch { }
                }
            }
            catch (Exception ex) { Debug.WriteLine(ex.Message); }
            return list;
        }

        public static async Task<List<PlaceItem>> GetNearbyPlacesByName(string name, double lat, double lo)
        {
            if (fb_access_token == "")
                await Get_FB_Access_Token();
            var list = new List<PlaceItem>();
            try
            {
                WebClient wc = new WebClient();
                var r = await wc.DownloadStringTaskAsync(new Uri(string.Format(fb_Places_Search_By_Name_Nearby, lat, lo, SettingUtils.Settings.MapSearchRadius, fb_access_token, name)));
                var jo = JObject.Parse(r);
                int count = 0;
                foreach (JObject item in (JArray)jo["data"])
                {
                    count++;
                    try
                    {
                        list.Add(new PlaceItem
                        {
                            ID=count,
                            Id = (string)item["id"],
                            Name = (string)item["name"],
                            latitude = (double)item["location"]["latitude"],
                            longitude = (double)item["location"]["longitude"],
                            street = (string)item["location"]["street"],
                            city = (string)item["location"]["city"],
                            state = (string)item["location"]["state"],
                            country = (string)item["location"]["country"],
                            zip = (string)item["location"]["zip"],
                            categoryName = (string)item["category_list"][0]["name"],
                            categoryId = (string)item["category_list"][0]["id"]
                        });
                    }
                    catch { }
                }
            }
            catch (Exception ex) { Debug.WriteLine(ex.Message); }
            return list;
        }

        public static async Task<List<PlaceItem>> GetNearbyPlaces(GeoCoordinate gps)
        {
            return await GetNearbyPlaces(gps.Latitude, gps.Longitude);
        }


        public static async Task<string> Get_FB_Places(string name)
        {
            if (fb_access_token == "")
                await Get_FB_Access_Token();
            WebClient wc = new WebClient();
            return await wc.DownloadStringTaskAsync(new Uri(string.Format(fb_Places_Search_By_Name, name)));
        }

        public static async void Get_FB_Friends()
        {
            if (fb_access_token == "")
                await Get_FB_Access_Token();
            try
            {
                WebClient wc = new WebClient();
                string result = await wc.DownloadStringTaskAsync(new Uri(string.Format(fb_Friend_List, fb_access_token)));
                JObject jo = JObject.Parse(result);
                ListFriends.Clear();
                foreach (JObject f in (JArray)jo["data"])
                {
                    ListFriends.Add(new FriendModel { Name = (string)f["name"], ID = (string)f["id"] });
                }
            }
            catch (Exception ex) { Debug.WriteLine(ex.Message); }
        }

    }

    public static class FbPrivacy
    {
        public static List<FbPrivacyModel> GetPrivacy()
        {
            List<FbPrivacyModel> list = new List<FbPrivacyModel>();
            list.Add(new FbPrivacyModel { Name = AppResources.Everyone, Code = "EVERYONE" });
            list.Add(new FbPrivacyModel { Name = AppResources.FOF, Code = "FRIENDS_OF_FRIENDS" });
            list.Add(new FbPrivacyModel { Name = AppResources.AllFriends, Code = "ALL_FRIENDS" });
            list.Add(new FbPrivacyModel { Name = AppResources.SomeFriends, Code = "SOME_FRIENDS" });
            list.Add(new FbPrivacyModel { Name = AppResources.Self, Code = "SELF" });
            list.Add(new FbPrivacyModel { Name = AppResources.NoFriends, Code = "NO_FRIENDS" });
            return list;
        }
    }

#region Model

    public class FbPrivacyModel
    {
        public string Name { get; set; }
        public string Code { get; set; }
    }

    public class FriendModel
    {
        public string Name { get; set; }
        public string ID { get; set; }
    }

    public class PhotoTag
    {
        public PhotoTag()
        {
            x = y = "0";
        }

        public string tag_uid { get; set; }
        public string tag_text { get; set; }
        public string x { get; set; }
        public string y { get; set; }
    }

    //public class FBPlace : PlaceItem
    //{
    //    public FBPlace(JObject jo = null)
    //    {
    //        if (jo != null)
    //        {
    //            Id = (string)jo["id"];
    //            Name = (string)jo["name"];
    //            latitude = (double)jo["location"]["latitude"];
    //            longitude = (double)jo["location"]["longitude"];
    //            longitude = (double)jo["location"]["longitude"];
    //            street = (string)jo["location"]["street"];
    //            city = (string)jo["location"]["city"];
    //            state = (string)jo["location"]["state"];
    //            country = (string)jo["location"]["country"];
    //            zip = (string)jo["location"]["zip"];
    //            categoryName = (string)jo["category_list"][0]["name"];
    //            categoryId = (string)jo["category_list"][0]["id"];
    //        }
    //    }

        //public string ID { get; set; }
        //public string Name { get; set; }
        //public double latitude { get; set; }
        //public double longitude { get; set; }
        //public string street { get; set; }
        //public string city { get; set; }
        //public string state { get; set; }
        //public string country { get; set; }
        //public string zip { get; set; }
        //public string categoryName { get; set; }
        //public string categoryId { get; set; }

    //}

#endregion

}